using UnityEngine;
using WebSocketSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Text;
using System;
using PimDeWitte.UnityMainThreadDispatcher;

public class GameController : MonoBehaviour
{
    public Transform[] team1Cubes;
    public Transform[] team2Cubes;
    public Transform[] team3Cubes;
    public Transform[] team4Cubes; // 新增
    public GameObject[] enemyPrefabs;
    public GameObject[] enemyPrefabs1;
    public GameObject[] enemyPrefabs2; // 新增
    public Dictionary<string, GameObject> enemies = new Dictionary<string, GameObject>();
    public Dictionary<string, int> userGiftCount = new Dictionary<string, int>();
    public WebSocket webSocket;
    public float moveSpeed = 0.0f;
    public float spawnRadius = 5.0f;

    void Start()
    {
        webSocket = new WebSocket("ws://192.168.1.10:8083/websocket");
        webSocket.OnMessage += OnWebSocketMessage;
        webSocket.Connect();
        Debug.Log("WebSocket connected to ws://192.168.1.10:8083/websocket");

        if (enemyPrefabs != null && enemyPrefabs.Length > 0 && team1Cubes.Length > 0 && team2Cubes.Length > 0)
        {
            // Do additional initialization if needed
        }
        else
        {
            Debug.LogError("Check references in the Inspector.");
        }
    }

    void Update()
    {
        foreach (var enemy in enemies.Values)
        {
            MoveEnemy(enemy);
        }
    }

    private void OnWebSocketMessage(object sender, MessageEventArgs e)
    {
        string message = e.Data;
        string utf8Message = Encoding.UTF8.GetString(Encoding.Default.GetBytes(message));
        try
        {
            JObject jsonData = JObject.Parse(utf8Message);
            HandleUserAction(jsonData);
        }
        catch (JsonReaderException ex)
        {
            Debug.LogError("Error parsing JSON: " + ex.Message);
        }
        if (!webSocket.IsAlive)
        {
            Debug.LogWarning("WebSocket connection closed, reconnecting...");
            webSocket.Connect();
            Debug.Log("WebSocket reco ws://192.168.1.10:8083/websocket");
        }
    }

    private void HandleUserAction(JObject jsonData)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() =>
        {
            try
            {
                if (jsonData["nickName"] != null)
                {
                    string username = jsonData["nickName"].ToString();

                    // 检查用户是否已生成预制体
                    if (!userGiftCount.ContainsKey(username))
                    {
                        userGiftCount[username] = 0;
                    }

                    if (jsonData["content"] != null)
                    {
                        // 处理 content 消息
                        if (userGiftCount[username] == 0)
                        {
                            int content;
                            if (int.TryParse(jsonData["content"].ToString(), out content))
                            {
                                GenerateEnemy(username, content);
                                userGiftCount[username]++;
                            }
                            else
                            {
                                Debug.LogError("无效的内容: " + jsonData.ToString());
                            }
                        }
                        else
                        {
                            Debug.LogWarning($"{username} 已在阵营生成预制体，不能再次生成");
                        }
                    }
                    else if (jsonData["count"] != null)
                    {
                        // 处理 count 消息
                        float count;
                        if (float.TryParse(jsonData["count"].ToString(), out count))
                        {
                            // 判断是否是第四个 cube 的生成需求
                            GenerateEnemyAtCube(username, count);
                        }
                        else
                        {
                            Debug.LogError("无效的 count 值: " + jsonData.ToString());
                        }

                        userGiftCount[username]++;
                    }
                    else if (jsonData["giftName"] != null)
                    {
                        // 处理 gift 消息
                        string giftName = jsonData["giftName"].ToString();
                        GenerateEnemy(username, giftName);
                        userGiftCount[username]++;
                    }
                    else
                    {
                        // 收到 {"nickName":"X***"} 时，在第三个 cube 的位置生成预制体
                        GenerateEnemyAtThirdCube(username);
                    }
                }
                else
                {
                    Debug.LogError("无效的用户数据在消息中.");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("HandleUserAction 错误: " + ex.Message);
                Debug.LogException(ex);
            }
        });
    }

    private void GenerateEnemyAtCube(string username, float count)
    {
        // 根据 count 值判断生成位置
        if (count == 1 && team4Cubes.Length > 0 && enemyPrefabs2.Length > 0)
        {
            Transform fourthCube = team4Cubes[UnityEngine.Random.Range(0, team4Cubes.Length)];
            // 修改生成位置为选定 cube 的上空
            Vector3 spawnPosition = fourthCube.position + new Vector3(0f, 5f, 0f);
            GenerateEnemy(username, spawnPosition, enemyPrefabs2);
        }
        else
        {
            Debug.LogError($"无效的 count 值或指定的 cube 或预制体数量不足，无法在指定 cube 位置生成预制体: {count}");
        }
    }

    private void GenerateEnemy(string username, Vector3 spawnPosition, GameObject[] enemyPrefabs2)
    {
        throw new NotImplementedException();
    }

    private void GenerateEnemyAtThirdCube(string username)
    {
        if (team3Cubes.Length > 0 && enemyPrefabs1.Length > 0)
        {
            Transform thirdCube = team3Cubes[UnityEngine.Random.Range(0, team3Cubes.Length)];
            GenerateEnemy(username, thirdCube, enemyPrefabs1);
        }
        else
        {
            Debug.LogError("指定的 cube 或预制体数量不足，无法在第三个 cube 位置生成预制体");
        }
    }

    private void GenerateEnemy(string username, Transform selectedCube, GameObject[] enemyPrefabs)
    {
        if (selectedCube != null && enemyPrefabs.Length > 0)
        {
            int prefabIndex = UnityEngine.Random.Range(0, enemyPrefabs.Length);
            GameObject selectedPrefab = enemyPrefabs[prefabIndex];
            Vector3 spawnPosition = GetRandomSpawnPosition(selectedCube.position);

            // 如果是第三个 cube，将生成位置上移
            if (Array.IndexOf(team3Cubes, selectedCube) >= 0)
            {
                spawnPosition.y += 0.2f;
            }

            Quaternion rotation = selectedCube.rotation;

            GameObject newEnemy = Instantiate(selectedPrefab, spawnPosition, rotation);
            Rigidbody enemyRigidbody = newEnemy.AddComponent<Rigidbody>();
            enemyRigidbody.freezeRotation = true;
            enemyRigidbody.useGravity = false;

            // 修改这里，确保名字包含用户名
            string uniqueKey = $"{selectedPrefab.name}_Variant(Clone)_{username}";
            newEnemy.name = uniqueKey;
            enemies.Add(uniqueKey, newEnemy);

            Debug.Log($"敌人生成在第三个 cube 位置{(Array.IndexOf(team3Cubes, selectedCube) >= 0 ? "上空附近" : "")}: {spawnPosition}, 玩家名字: {username}");
        }
        else
        {
            Debug.LogError("指定的 cube 或预制体数量不足，无法生成预制体");
        }
    }

    private void GenerateEnemy(string username, int content)
    {
        int prefabIndex;
        Transform selectedCube;

        if (content == 1)
        {
            prefabIndex = UnityEngine.Random.Range(0, 4);
            selectedCube = GetRandomCube(team1Cubes);
        }
        else if (content == 2)
        {
            prefabIndex = UnityEngine.Random.Range(4, 8);
            selectedCube = GetRandomCube(team2Cubes);
        }
        else
        {
            Debug.LogError("无效的内容: " + content);
            return;
        }

        GameObject selectedPrefab = enemyPrefabs[prefabIndex];
        Vector3 spawnPosition = GetRandomSpawnPosition(selectedCube.position);

        // 计算朝向相反的旋转方向
        Quaternion rotation = (content == 1) ? selectedCube.rotation : Quaternion.LookRotation(-selectedCube.forward);

        GameObject newEnemy = Instantiate(selectedPrefab, spawnPosition, rotation);
        Rigidbody enemyRigidbody = newEnemy.AddComponent<Rigidbody>();
        enemyRigidbody.freezeRotation = true;
        enemyRigidbody.useGravity = false;
        string uniqueKey = $"{content}_{username}";
        newEnemy.name = $"{selectedPrefab.name}_{uniqueKey}";
        enemies.Add(uniqueKey, newEnemy);

        Debug.Log($"敌人生成在阵营 {content} 的 cube 位置: {spawnPosition}, 玩家名字: {username}");
    }

    private void GenerateEnemy(string username, string giftName)
    {
        string uniqueKey = GenerateUniqueKey(username, giftName);

        if (enemies.ContainsKey(uniqueKey))
        {
            Debug.LogWarning($"相同的键已存在: {uniqueKey}, 跳过生成敌人");
            return;
        }

        int prefabIndex = UnityEngine.Random.Range(0, enemyPrefabs.Length);
        GameObject selectedPrefab = enemyPrefabs[prefabIndex];
        int content = GetGiftCamp(giftName);
        Transform selectedCube = (content == 1) ? GetRandomCube(team1Cubes) : GetRandomCube(team2Cubes);
        Vector3 spawnPosition = GetRandomSpawnPosition(selectedCube.position);
        // 计算朝向相反的旋转方向
        Quaternion rotation = (content == 1) ? selectedCube.rotation : Quaternion.LookRotation(-selectedCube.forward);
        //Quaternion rotation = selectedCube.rotation;

        GameObject newEnemy = Instantiate(selectedPrefab, spawnPosition, rotation);
        Rigidbody enemyRigidbody = newEnemy.AddComponent<Rigidbody>();
        enemyRigidbody.freezeRotation = true;
        enemyRigidbody.useGravity = false;
        newEnemy.name = $"{selectedPrefab.name}-Variant(Clone)-{username}-{giftName}"; // 修改这里，确保名字包含用户名
        enemies.Add(uniqueKey, newEnemy);

        Debug.Log($"敌人生成在阵营 {content} 的 cube 位置: {spawnPosition}, 玩家名字: {username}, 礼物名字: {giftName}");
    }

    private void MoveEnemy(GameObject enemy)
    {
        if (enemy == null)
        {
            return;
        }

        enemy.transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
    }

    public void RemoveEnemyFromList(string username, string giftName)
    {
        string uniqueKey = GenerateUniqueKey(username, giftName);

        if (enemies.ContainsKey(uniqueKey))
        {
            GameObject enemyToRemove = enemies[uniqueKey];
            enemies.Remove(uniqueKey);
            Destroy(enemyToRemove);

            if (userGiftCount.ContainsKey(username))
            {
                userGiftCount[username] = 0;
            }
        }
    }

    private void OnDestroy()
    {
        if (webSocket != null && webSocket.IsAlive)
        {
            webSocket.Close();
        }
    }

    private int GetGiftCamp(string giftName)
    {
        int hashCode = giftName.GetHashCode();
        int camp = (hashCode % 2 == 0) ? 2 : 1;
        return camp;
    }

    private Transform GetRandomCube(Transform[] cubes)
    {
        return cubes[UnityEngine.Random.Range(0, cubes.Length)];
    }

    private Vector3 GetRandomSpawnPosition(Vector3 basePosition)
    {
        Vector2 randomOffset = UnityEngine.Random.insideUnitCircle.normalized * spawnRadius;
        return basePosition + new Vector3(randomOffset.x, 0.0f, randomOffset.y);
    }

    private string GenerateUniqueKey(string username, string giftName)
    {
        Guid uniqueGuid = Guid.NewGuid();
        string uniqueKey = uniqueGuid.ToString();
        uniqueKey += $"-{giftName}_{username}";
        return uniqueKey;
    }
}
